package com.hong.spring.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 *
 * 功能描述: 服务端监听器
 *
 * 方法	描述
 * handlerAdded	Handler 被加入 Pipeline 时触发（仅仅触发一次）
 * channelRegistered	channelRegistered 注册成功时触发
 * channelActive	channel 连接就绪时触发
 * channelRead	channel 有数据可读时触发
 * channelReadComplete	channel 有数据可读，并且读完时触发
 * channelInactive	channel 断开时触发
 * channelUnregistered	channel 取消注册时触发
 * handlerRemoved	handler 被从 Pipeline 移除时触发
 *
 * @param:
 * @return:
 * @auther: csh
 * @date: 2021/1/15 16:05
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    /**
     *
     * 功能描述: 收到消息方法！
     *
     * @param: 
     * @return: 
     * @auther: csh
     * @date: 2021/1/18 15:13
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("client msg " + byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("client address " + ctx.channel().remoteAddress());
        ctx.writeAndFlush(byteBuf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello client i'm hong server!",CharsetUtil.UTF_8));
    }
    /**
     *
     * 功能描述: 异常触发
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2021/1/18 15:16
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("通道断开:"+ctx.channel().id());
        super.channelInactive(ctx);
    }
}
